package com.backend.system.service.processors.role;

import cn.hutool.core.bean.BeanUtil;
import com.backend.system.beans.role.RoleAddOrUpdateReq;
import com.backend.system.common.CustomException;
import com.backend.system.common.annotation.ProcessorBean;
import com.backend.system.common.enums.ActionTypeEnum;
import com.backend.system.common.processor.AbstractProcessorTemplate;
import com.backend.system.common.processor.ProcessorContext;
import com.backend.system.dao.entity.Role;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * 新增或修改角色处理器
 *
 * @author backend-manage
 */
@Slf4j
@Component
@ProcessorBean(action = ActionTypeEnum.ROLE_ADD_OR_UPDATE)
public class RoleAddOrUpdateProcessor extends AbstractProcessorTemplate<RoleAddOrUpdateReq, Boolean> {

    private Role role;

    private boolean isUpdateRole;

    @Override
    protected void init(ProcessorContext<RoleAddOrUpdateReq> context) {
        RoleAddOrUpdateReq req = context.getData();
        role = null;
        isUpdateRole = Objects.nonNull(req.getId());

        if (isUpdateRole) {
            role = roleService.getById(req.getId());
            if (Objects.isNull(role)) {
                throw CustomException.argsError("角色不存在");
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean handle(ProcessorContext<RoleAddOrUpdateReq> context) {
        RoleAddOrUpdateReq req = context.getData();
        boolean result;

        // 更新角色
        if (isUpdateRole) {
            BeanUtil.copyProperties(req, role);
            result = roleService.updateById(role);
        } else {
            // 新增角色
            BeanUtil.copyProperties(req, role);
            result = roleService.save(role);
        }
        return result;
    }
}
